package com.pz.sjxypz;

import com.pub.dbtools.DBOperator;
import com.pub.dbtools.DataGrid;
import com.pub.dbtools.DataSimpDto;
import com.pub.dbtools.StaticOper;
import com.pz.sjypz.sjypzEntity;
import com.util.CodeUtil;

import net.sf.ehcache.search.expression.And;

import org.apache.hadoop.hive.ql.parse.HiveParser_IdentifiersParser.stringLiteralSequence_return;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.LogUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Title: Controller
 * @Description: jeecg_demo
 * @author onlineGenerator
 * @date 2017-03-22 20:11:23
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/sjxypzController")
public class sjxypzController extends BaseController {


    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(sjxypzController.class);



    @Autowired
    private SystemService systemService;
    @Autowired
    private sjxypzServiceI sjxypzService;

    /**
     * 采用minidao查询数据
     * @param request
     * @return
     */
    //sjxypzController.do?mlist
    @RequestMapping(params = "entermain")
    public ModelAndView entermain(HttpServletRequest request) {
    	request.setAttribute("m","pz/sjxypz");
        return new ModelAndView("common/entermain");
    }

    /**
     * 第1表列表数据显示准备
     /fwq/com/jt/scld/entermain.jsp
     */
    @RequestMapping(params ="maintitle")
    public ModelAndView mainTitle(HttpServletRequest request) {
        System.out.print("======maintitle");
     //   List<ScldEntity> tp= DBQuerySql.findObjForJdbc("select * from f_ld_scld",1,2, com.jt.scld.entity.ScldEntity.class);

        HttpSession session = ContextHolderUtils.getSession();
        String cheight = (String) session.getAttribute("pub_pm_gd");
        String cjmheight = (String) session.getAttribute("pub_pm_jm");
        System.out.println("cheight="+cheight);

        String rdatasizes = StringUtil.getDataSize("上半屏", cheight, cjmheight,
                "50");
        String rdatasizex = StringUtil.getDataSize("下半屏", cheight, cjmheight,
                "50");
        String rdatasize = StringUtil.getDataSize("全屏", cheight, cjmheight,
                "50");
        session.setAttribute("pub_datasize", rdatasize);
        session.setAttribute("pub_datasizes", rdatasizes);
        session.setAttribute("pub_datasizex", rdatasizex);
       /* return new ModelAndView("com/jt/scld/main");*/
        return new ModelAndView("com/pz/sjxypz/l");
    }





    @RequestMapping(params = "mlistDatagrid")
    public void mlistDatagrid(HttpServletRequest request, HttpServletResponse response, org.jeecgframework.core.common.model.json.DataGrid dataGrid) {
        /**
         * 注意：minidao会遵循springjdbc规则，会自动把数据库以下划线的字段，转化为驼峰写法
         * 例如数据库表字段：{USER_NAME}
         * 转化实体对应字段：{userName}
         */
        String selesql = " select PK_PROTOCOL id,fd_pname,fd_kq from t_jk_protocol ";
        DataSimpDto a=new DataSimpDto(selesql);

       // List<JeecgDemoEntity> list = jeecgMinidaoDao.getAllEntities(jeecgDemo, dataGrid.getPage(), dataGrid.getRows());
       /* dataGrid= sjxypzService.getOneList(dataGrid);*/

        Integer count = a.getTotRecord();
        dataGrid.setTotal(count);
        dataGrid.setResults(a.getDataDtomap());
        dataGrid.setFields(a.getFieldName());

       // String total_salary = String.valueOf(jeecgMinidaoDao.getSumSalary());
		/*
		 * 说明：格式为 字段名:值(可选，不写该值时为分页数据的合计) 多个合计 以 , 分割
		 */

      //  dataGrid.setFooter("salary:"+(total_salary.equalsIgnoreCase("null")?"0.0":total_salary)+",age,email:合计");
        TagUtil.datagrids(response, dataGrid);
    }

    @RequestMapping(params ="subtitle")
    private String subMake(HttpSession session, HttpServletRequest request) {
        String keyid = request.getParameter("keyid");
        System.out.print("keyid="+keyid);
        String pno=request.getParameter("pno");
        System.out.print("pno="+pno);
        session.setAttribute("pub_keyid"+pno, keyid);
        session.setAttribute("pub_pno", pno);
        System.out.print("pno="+pno);
        return "/com/pz/sjxypz/l"+pno;
    }
    @RequestMapping(params = "sublistDatagrid")
    public void sublistDatagrid(HttpSession session,HttpServletRequest request, HttpServletResponse response, org.jeecgframework.core.common.model.json.DataGrid dataGrid) {
        /**
         * 注意：minidao会遵循springjdbc规则，会自动把数据库以下划线的字段，转化为驼峰写法
         * 例如数据库表字段：{USER_NAME}
         * 转化实体对应字段：{userName}
         */
        String pno=(String)session.getAttribute("pub_pno");
        String keyid = (String) session.getAttribute("pub_keyid"+pno);
        String selesql="";
        if (pno.equals("0")){
            selesql = " select pk_dformat id,fd_data,fd_outtype,fd_outname,fd_split,fd_max,fd_rule from t_jk_dformat ";
            selesql+=" where pk_protocol='" + keyid + "'";
        }
        if  (pno.equals("1")){
             selesql = " select pk_ditem id,fd_order,fd_item,fd_default,fd_iftranslate,fd_prefix,fd_postfix from t_jk_ditem  ";
             selesql+=" where pk_dformat='" + keyid + "'";
        }
        DataSimpDto a=new DataSimpDto(selesql);
        Integer count = a.getTotRecord();
        dataGrid.setTotal(count);
        dataGrid.setResults(a.getDataDtomap());
        dataGrid.setFields(a.getFieldName());

        //  dataGrid.setFooter("salary:"+(total_salary.equalsIgnoreCase("null")?"0.0":total_salary)+",age,email:合计");
        TagUtil.datagrids(response, dataGrid);
    }

    /**
     * 数据协议配置主表新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "edit")
    public ModelAndView Edit(String p,String id,HttpSession session,HttpServletRequest req) {
        String t="",fk="";
        if (StringUtil.isNotEmpty(p)){
            t=p;
            Map<String,Object> map = new HashMap<String,Object>();
            if (t.equals("0"))fk="pk_protocol";
            if (t.equals("1"))fk="pk_dformat";
            System.out.println("pub_keyid"+t+"="+session.getAttribute("pub_keyid"+t));
            map.put(fk,(String) session.getAttribute("pub_keyid"+t));
            req.setAttribute("t1", map);
        }
        if (StringUtil.isNotEmpty(id)) {

            String sql="select * from t_jk_protocol where pk_protocol= '"+id+"'";

            if (t.equals("0")){
                sql="select * from t_jk_dformat where pk_dformat= '"+id+"'";
            }
            if (t.equals("1")){
                sql="select * from t_jk_ditem where pk_ditem= '"+id+"'";
            }

            DataSimpDto a=new DataSimpDto(sql);
            Map<String,Object> map = new HashMap<String,Object>();
            for (int i=0;i<a.getTotField();i++){
                map.put(a.getFieldName(i),a.getDataValue(i,0));
            }
            req.setAttribute("t1", map);
        }
        return new ModelAndView("com/pz/sjxypz/edit"+t);
    }

    @RequestMapping(params = "doedit")
    @ResponseBody
    public AjaxJson doEdit(String p,String id,HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();

//        String pkProtocol = UUID.randomUUID().toString();
//        
//        sjxypz.setPkProtocol(pkProtocol);
//        StringBuffer sql = new StringBuffer("insert into t_jk_protocol value(");
//        sql.append("'"+sjxypz.getPkProtocol()+"',");
//        sql.append("'"+sjxypz.getFdPname()+"',");
//        sql.append("'"+sjxypz.getFdKq()+"');");
//        try{
//            systemService.executeSql(sql.toString());
//        }catch (Exception e){
//            LogUtil.log("数据协议信息添加失败", e.getMessage());
//            ajaxJson.setSuccess(false);
//            ajaxJson.setMsg(e.getMessage());
//        }
//        ajaxJson.setMsg("数据协议信息添加成功");
//        return ajaxJson;
        Hashtable<String, String> tmphash = new Hashtable<String, String>();
        Enumeration newparas = req.getParameterNames();
        String tmpfieldname = "";
        while (newparas.hasMoreElements()) {
            tmpfieldname = (String) newparas.nextElement();
            if (tmpfieldname.startsWith("pk_")||tmpfieldname.startsWith("fd_")){
                tmphash.put(tmpfieldname.toLowerCase(),
                		req.getParameter(tmpfieldname));
            }
        }
        
        
       /* 将t_syj_systag表中fd_sm值放入l1页面的fd_item中 */ 
        if(StringUtil.isNotEmpty(p)){
        	if(p.equals("1")){
        	String pk_systag = req.getParameter("pk_systag");
        	String sqltag = "select fd_tag from t_sjy_systag where pk_systag = '" + pk_systag + "'";
           	DataSimpDto b=new DataSimpDto(sqltag);
           	String fd_tag = b.getDataValue("fd_tag", 0);
           	tmphash.put("fd_item", fd_tag);
        	}
        }
        
        String sql="";
        try{
            String pk="pk_protocol";String tb="t_jk_protocol";
            if (StringUtil.isNotEmpty(p)){
                if (p.equals("0")){
                    pk="pk_dformat";tb="t_jk_dformat";
                }
                if (p.equals("1")){
                    pk="pk_ditem";tb="t_jk_ditem";
                }
            }
            if (StringUtil.isNotEmpty(req.getParameter(pk))) {
                sql= StaticOper.makeUpdSql(tb,tmphash,pk,req.getParameter(pk));
            }else{
                tmphash.remove(pk);
                sql= StaticOper.makeInsSql(tb,tmphash);
            }
            System.out.println(sql);
            systemService.executeSql(sql.toString());

        }catch (Exception e){
            LogUtil.log("保存失败", e.getMessage());
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg(e.getMessage());
        }
        ajaxJson.setMsg("保存成功");
        return ajaxJson;
    } 
    
    /**
     * 删除行
     */
    @RequestMapping(params = "dodel")
    @ResponseBody
    public AjaxJson dodel(String p,String id, HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();

        if (StringUtil.isNotEmpty(id)) {
            ArrayList arr=new ArrayList();
            String sql="";
            if (p == null){
                sql = "delete from t_jk_ditem where pk_dformat in (select pk_dformat from t_jk_dformat where pk_protocol = '"+id+"')";
                arr.add(sql);
                sql = "delete from t_jk_dformat where pk_protocol = '"+id+"'";
                arr.add(sql);
                sql = "delete from t_jk_protocol where pk_protocol = '"+id+"'";
                arr.add(sql);
            }else {
            	if(p.equals("0")){
                  sql = "delete from t_jk_ditem where pk_dformat = '"+id+"'";
                  arr.add(sql);
                  sql = "delete from t_jk_dformat where pk_dformat = '"+id+"'";
                  arr.add(sql);
               }
	             if (p.equals("1")){
	                 sql = "delete from t_jk_ditem where pk_ditem = '"+id+"'";
	                 arr.add(sql);
	           }

			}
             
            try {
                DBOperator.execSql(arr);
            }catch(Exception e){
                LogUtil.log("删除失败", e.getMessage());
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg(e.getMessage());
            }
            ajaxJson.setMsg("删除成功");
        }
        return ajaxJson;
    }
    
    
}
